const { devDebug } = require("../settings");

async function search(searchText, searchData) {
  console.log('搜索字段：' + searchText);
  let dateRange = [];
  if (searchText) {
    const searchObj = JSON.parse(searchText);
    dateRange = searchObj.dateRange;
    searchText = searchObj.searchText;
  }
  const resList = await new Promise(resolve => {
    wx.cloud.callFunction({
      name: 'db_appointment',
      data: {
        funcName: 'query',
        searchText: searchText,
        searchData: searchData,
        dateRange: dateRange,
      },
      success: (r) => resolve(r.result),
    });
  })
  if (devDebug) console.log('预约搜索结果', resList);
  return resList.map(o => {
    o.date = new Date(o.date_ts).Format('yyyy-MM-dd');
    o.valid_cnt = o.sku_valid_cnt ? `共 ${o.sku_valid_cnt} 个可预约的时段` : '已满'
    return o;
  })
}

async function viewAppointment(appointmentId) {
  wx.navigateTo({
    url: `/pages/reservation/appointment?appointmentId=${appointmentId}`,
  })
}

async function updateAppointment(appointmentId) {
  wx.navigateTo({
    url: `/pages/reservation/appointment?appointmentId=${appointmentId}&disabled=0`,
  })
}

module.exports = {
  title: 'stadium_name',
  subtitle: '',
  data_keys: [
    { k: 'date', v: '预约日期' },
    { k: 'valid_cnt', v: '剩余空场' },
  ],
  data_btns: [
    { label: '查看当日预约', funcName: 'viewAppointment' },
    // { label: '修改当日预约', funcName: 'updateAppointment' },
  ],
  search_placeholder: '搜索球馆名称',
  header_btn: { text: '新建预约', url: '/pages/creator/appointment' },
  tabs: [
    { label: '搜索结果', searchData: {} },
  ],
  viewAppointment,
  updateAppointment,
  search,
}